# -*- coding: utf-8 -*-
# @Time    : 2021/3/11 10:26
# @Author  : zcn
# @Software: PyCharm
from bson import ObjectId
from fastapi import APIRouter
from re_common.baselibrary.tools.all_requests.aiohttp_request import AioHttpRequest
from re_common.baselibrary.tools.all_requests.mrequest import MRequest
from re_common.baselibrary.utils.basedict import BaseDicts
from re_common.baselibrary.utils.basedir import BaseDir
from re_common.baselibrary.utils.basefile import BaseFile
from re_common.baselibrary.utils.basetime import MCalendar, BaseTime

from apps.allsubdb.err_analysis_server.models import ErrSignal, err2dir, \
    ClientGetFail, ServerGetExceptSqlId, ServerGetExceptSqlBatch, DelFromMongo, CountPost
from apps.core.global_model import InputPlatformModel
from apps.core.m_route import ContextIncludedRoute
from apps.core.return_info import ReturnInfo, SUCCESS, FAILED
from apps.sql_app.mmongodb import Coll
from settings import get_settings

router = APIRouter(route_class=ContextIncludedRoute)

cur_path = BaseDir.get_file_dir_absolute(__file__)
top_path = BaseDir.get_upper_dir(cur_path, -4)
sPath = BaseFile.get_new_path(top_path, "err_solution")


####################################################################################################################
# 以下为函数区test
####################################################################################################################


async def task_select(task_name, task_tag, errdate, judge):
    # 等于该日期 无task_tag
    sql_no_task_tag_equal = "select err_type, batch, err_str, counts, type_name from err_analysis where task_name = '{}' and LEFT(batch,8) = '{}'"
    # 大于等于该日期 无task_tag
    sql_no_task_tag_gt = "select err_type, batch, err_str, counts, type_name from err_analysis where task_name = '{}' and LEFT(batch,8) >= '{}'"
    # 小于等于该日期 无task_tag
    sql_no_task_tag_lt = "select err_type, batch, err_str, counts, type_name from err_analysis where task_name = '{}' and LEFT(batch,8) <= '{}'"
    # 不需任何其他条件 仅取task_name
    sql_nothing = "select err_type, batch, err_str, counts, type_name from err_analysis where task_name = '{}'"

    # 等于该日期
    sql_task_tag_equal = "select err_type, batch, err_str, counts, type_name from err_analysis where task_name = '{}' and task_tag = '{}' and LEFT(batch,8) = '{}'"
    # 大于等于该日期
    sql_task_tag_gt = "select err_type, batch, err_str, counts, type_name from err_analysis where task_name = '{}' and task_tag = '{}' and LEFT(batch,8) >= '{}'"
    # 小于等于该日期
    sql_task_tag_lt = "select err_type, batch, err_str, counts, type_name from err_analysis where task_name = '{}' and task_tag = '{}' and LEFT(batch,8) <= '{}'"
    # 不需任何其他条件 仅取task_name和task_tag
    sql_step = "select err_type, batch, err_str, counts, type_name from err_analysis where task_name = '{}' and task_tag = '{}'"
    from main import app
    pool = app.state.pool
    if task_tag == "nothing":
        if errdate == "nothing":
            async with pool.acquire() as conn:
                async with conn.cursor() as cur:
                    await cur.execute(sql_nothing.format(task_name))
                    data = await cur.fetchall()
                    await cur.close()
                    conn.close()
        else:
            if judge == "1":
                async with pool.acquire() as conn:
                    async with conn.cursor() as cur:
                        await cur.execute(sql_no_task_tag_gt.format(task_name, errdate))
                        data = await cur.fetchall()
                        await cur.close()
                        conn.close()
            elif judge == "2":
                async with pool.acquire() as conn:
                    async with conn.cursor() as cur:
                        await cur.execute(sql_no_task_tag_lt.format(task_name, errdate))
                        data = await cur.fetchall()
                        await cur.close()
                        conn.close()
            else:
                async with pool.acquire() as conn:
                    async with conn.cursor() as cur:
                        await cur.execute(sql_no_task_tag_equal.format(task_name, errdate))
                        data = await cur.fetchall()
                        await cur.close()
                        conn.close()

    else:
        if errdate == "nothing":
            async with pool.acquire() as conn:
                async with conn.cursor() as cur:
                    await cur.execute(sql_step.format(task_name, task_tag))
                    data = await cur.fetchall()
                    await cur.close()
                    conn.close()
        else:
            if judge == "1":
                async with pool.acquire() as conn:
                    async with conn.cursor() as cur:
                        await cur.execute(sql_task_tag_gt.format(task_name, task_tag, errdate))
                        data = await cur.fetchall()
                        await cur.close()
                        conn.close()
            elif judge == "2":
                async with pool.acquire() as conn:
                    async with conn.cursor() as cur:
                        await cur.execute(sql_task_tag_lt.format(task_name, task_tag, errdate))
                        data = await cur.fetchall()
                        await cur.close()
                        conn.close()
            else:
                async with pool.acquire() as conn:
                    async with conn.cursor() as cur:
                        await cur.execute(sql_task_tag_equal.format(task_name, task_tag, errdate))
                        data = await cur.fetchall()
                        await cur.close()
                        conn.close()
    return data


async def task_delete(err_id, err_batch):
    sql = f"delete from err_analysis where err_type = '{err_id}' and batch = '{err_batch}'"
    from main import app
    pool = app.state.pool
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(sql)
            await conn.commit()


# def save_err_id(err_type_name, one_id, type_name, batch):
#     err_file_name = BaseFile.get_new_path(sPath, type_name, batch)
#     BaseDir.create_dir(err_file_name)
#     save_file = BaseFile.get_new_path(err_file_name, err_type_name + ".txt")
#     one_id = one_id + "\n"
#     with open(save_file, mode="a", encoding="utf-8") as f:
#         f.write(one_id)
#         f.close()


async def str_calcula(err_type_name, type_name, batch, judge="0"):
    '''

    :param err_type_name:
    :param type_name:
    :param batch:
    :param judge: 0 为判断是否存在该数据, 1判断该数据长度是否超标
    :return:
    '''

    sql = ""
    if judge == "0":
        sql = f"select count(*) from err_analysis where err_type = '{err_type_name}' and `batch` = '{batch}' and type_name = '{type_name}'"
    if judge == "1":
        sql = f"select count(*) from err_analysis where LENGTH(err_str) > 10000 and err_type like '%{err_type_name}%' and `batch` = '{batch}' and type_name = '{type_name}'"
    from main import app
    pool = app.state.pool
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(sql)
            data = await cur.fetchone()
            await cur.close()
            conn.close()

    return data[0]


async def get_mysql(type_name, batch, judge="0"):
    sql = ""
    if judge == "0":
        sql = f"select err_str from err_analysis where `batch` = '{batch}' and type_name = '{type_name}'"

    from main import app
    pool = app.state.pool
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(sql)
            data = await cur.fetchall()
            await cur.close()
            conn.close()
    return data


async def save_sql_id(err_type_name, type_name, batch, one_id, judge="0"):
    '''

    :param err_type_name:
    :param type_name:
    :param batch:
    :param one_id:
    :param judge: 用于判断使用哪个sql
    :return:
    '''
    sql = ""
    task_name = err_type_name.split("_")[0]
    task_tag = err_type_name.split("_")[1]
    if judge == "0":
        sql = f"insert into err_analysis(err_type, task_name, task_tag, `batch`, err_str, type_name) values('{err_type_name}', '{task_name}', '{task_tag}', '{batch}', '{one_id}', '{type_name}')"
    if judge == "1":
        sql = f"update err_analysis set err_str = CONCAT(err_str, ';{one_id}') where err_type = '{err_type_name}' and `batch` = '{batch}' and type_name = '{type_name}'"
    from main import app
    pool = app.state.pool
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(sql)
            await conn.commit()


def time_solve(time_str):
    time_format = "-".join([time_str[0:4], time_str[4:6], time_str[-2:]])
    return time_format


####################################################################################################################
# 以下为API区
####################################################################################################################

# ----------------------------------------------------------------------------------------------------------------
# client_api_fail表区
# ----------------------------------------------------------------------------------------------------------------

@router.post("/err_analysis/err_get")
async def get_task(input: InputPlatformModel[ErrSignal]):
    return_info = ReturnInfo()
    task_name = input.data.task_name
    task_tag = input.data.task_tag
    errdate = input.data.err_date
    judge = input.data.judge

    datas = await task_select(task_name, task_tag, errdate, judge)
    if datas:
        return_info.status = SUCCESS
        return_info.msg_code = 200
        return_info.msg = "错误获取成功"
        return_info.data = datas
        return return_info.todict()
    else:
        return_info.status = FAILED
        return_info.msg_code = 200
        return_info.msg = "获取失败, 数据库内不存在符合输入参数的数据"
        return_info.data = datas
        return return_info.todict()


# @router.post("/err_analysis/err_del")
# async def get_task(input: InputPlatformModel[ErrSignal]):
#     '''
#
#     :param input: 这个是以前的老代码  针对存储的txt去进行删除, 后续看是否改动,暂时不动这个API  也不启用
#     :return:
#     '''
#     return_info = ReturnInfo()
#     task_name = input.data.task_name
#     task_tag = input.data.task_tag
#     errdate = input.data.err_date
#     judge = input.data.judge
#     # type_name = input.data.type_name
#     client_api_fail = Coll().get_errs()
#     client_except = Coll().get_errs_part2()
#
#     datas = await task_select(task_name, task_tag, errdate, judge)
#     if datas:
#         if errdate == "nothing":
#             await client_api_fail.delete_many({"task_name": task_name, "task_tag": task_tag})
#             await client_except.delete_many({"task_name": task_name, "task_tag": task_tag})
#         else:
#             for one_id in datas:
#                 err_id = one_id[0]
#                 err_batch = one_id[1]
#                 type_name = one_id[4]
#                 if type_name == "client_api_fail":
#                     dir_path = BaseFile.get_new_path(sPath, type_name, err_batch, err_id + ".txt")
#                     ids = BaseFile.read_line(dir_path)
#                     for id1 in ids:
#                         await client_api_fail.delete_many({"_id": id1})
#                     await task_delete(err_id, err_batch)
#                 else:
#                     dir_path = BaseFile.get_new_path(sPath, type_name, err_batch, err_id + ".txt")
#                     ids = BaseFile.read_line(dir_path)
#                     for id1 in ids:
#                         await client_except.delete_many({"_id": id1})
#                     await task_delete(err_id, err_batch)
#
#         return_info.status = SUCCESS
#         return_info.msg_code = 200
#         return_info.msg = "错误删除成功"
#         return_info.data = datas
#         return return_info.todict()
#     else:
#         return_info.status = FAILED
#         return_info.msg_code = 200
#         return_info.msg = "错误删除失败, 请检查传入参数,数据库内未找到符合参数的数据"
#         return_info.data = datas
#         return return_info.todict()


@router.post("/err_analysis/err_save2mysql")
async def get_task(input: InputPlatformModel[err2dir]):
    '''

    :param input: 存入MYsql 由于longtext格式最高存储的也可能存放不下,故使用分段式存储,将一条数据分成多条的方式进行存储
    :return:
    '''
    return_info = ReturnInfo()
    err_type_name = input.data.err_type_name
    one_id = input.data.one_id
    type_name = input.data.type_name
    batch = input.data.batch
    # 判断该条信息  主信息 是否存在
    data = await str_calcula("★".join([err_type_name, "0"]), type_name, batch)

    if data == 0:
        # 不存在则insert
        err_type_name = "★".join([err_type_name, str(data)])
        await save_sql_id(err_type_name, type_name, batch, one_id)
    else:
        # 存在则判断 主信息是否 超标
        data1 = await str_calcula(err_type_name, type_name, batch, judge="1")
        if data1 == 0:
            err_type_name = "★".join([err_type_name, str(data1)])
            # 未超标则update到 主信息 内
            await save_sql_id(err_type_name, type_name, batch, one_id, judge="1")
        else:
            # 若超标则 以获取的 数字与主信息的err_type 进行组合 继续进行判定
            err_type_name = "★".join([err_type_name, str(data1)])
            data2 = await str_calcula(err_type_name, type_name, batch)
            if data2 == 0:
                # 不存在则insert
                await save_sql_id(err_type_name, type_name, batch, one_id)
            else:
                # 未超标则update到 子信息 内
                await save_sql_id(err_type_name, type_name, batch, one_id, judge="1")

    return_info.status = SUCCESS
    return_info.msg_code = 200
    return_info.msg = "errID已存入mysql"
    return_info.data = "OK"
    return return_info.todict()


# 获取err_client_fail错误的id, 以便后续删除
@router.post("/errs_analysis/err_client_fail_find")
async def get_client_fail(input: InputPlatformModel[CountPost]):
    """
    获取err_client_fail错误的id, 以便后续删除
     这里的目标结构是 {"batch": [{"err_type_name": "", "name_counts": "", "ids": ""},
                                {"err_type_name": "", "name_counts": "", "ids": ""}]}
    再以[{"err_type_name": "", "name_counts": "", "ids": "",batch:""}]的格式传出去
    name_counts:指的 chaoxingjournal_chaoxinghome_timeout★0 后面的0 之类的计数,因为部分ID过长
                导致分条存放, 用来分辨归属
    :return:
    """
    return_info = ReturnInfo()
    page_counts = input.data.page_counts
    counts = input.data.counts
    jump_counts = page_counts * counts
    sql_forward = f"select err_type, batch, err_str from err_analysis where type_name = 'client_api_fail' and id >= (SELECT id FROM `err_analysis` where type_name = 'client_api_fail' ORDER BY id LIMIT {jump_counts}, 1) limit {counts}"

    from main import app
    pool = app.state.pool
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(sql_forward)
            err_names = await cur.fetchall()
            await cur.close()
            conn.close()
    data_list = list()
    whole_dict = dict()
    model_dict = {"err_type_name": "", "name_counts": "", "err_str": "", "ids": ""}
    if len(err_names) == 0:
        return_info.status = SUCCESS
        return_info.msg_code = 200
        return_info.msg = "错误处理完毕, 无新内容进入"
        return_info.data = err_names
        return return_info.todict()
    else:
        for err_name in err_names:
            sql = f"select err_type, batch, err_str from err_analysis where err_type like '{err_name[0]}%' and batch = '{err_name[1]}' and type_name = 'client_api_fail_save_id'"
            from main import app
            pool = app.state.pool
            async with pool.acquire() as conn:
                async with conn.cursor() as cur:
                    await cur.execute(sql)
                    data = await cur.fetchall()
                    await cur.close()
                    conn.close()
            for row in data:
                a_list = row[0].split("★")
                # 以batch作为键, 以dict3作为值
                one_list = BaseDicts().is_dict_exit_key(whole_dict, row[1], default=[])
                if len(one_list) == 0:
                    whole_dict[row[1]] = list()
                    dict4 = model_dict.copy()
                    dict4["err_type_name"] = a_list[0]
                    dict4["name_counts"] = a_list[1]
                    dict4["err_str"] = err_name[2]
                    dict4["ids"] = row[2]
                    whole_dict[row[1]].append(dict4)
                else:
                    if a_list[0] in str(one_list):
                        for i in one_list:
                            if i["err_type_name"] == a_list[0]:
                                i["name_counts"] = i["name_counts"] + "," + a_list[1]
                                i["ids"] = ";".join([i["ids"], row[2]])
                    else:
                        dict4 = model_dict.copy()
                        dict4["err_type_name"] = a_list[0]
                        dict4["name_counts"] = a_list[1]
                        dict4["err_str"] = err_name[2]
                        dict4["ids"] = row[2]
                        whole_dict[row[1]].append(dict4)
        for k, v in whole_dict.items():
            for one_dict in v:
                one_dict["batch"] = k
                data_list.append(one_dict)

        return_info.status = SUCCESS
        return_info.msg_code = 200
        return_info.msg = "错误ID获取成功"
        return_info.data = data_list
        return return_info.todict()


# 删除单条错误,在MongoDB内, 针对client_api_fail表
@router.post("/errs_analysis/err_client_fail_del_one")
async def get_client_fail(input: InputPlatformModel[ServerGetExceptSqlId]):
    return_info = ReturnInfo()
    # 将就用这个model,类型都一样
    _id = input.data.ids
    client_api_fail = Coll().get_errs()
    client_api_fail.delete_one({"_id": ObjectId(_id)})
    return_info.status = SUCCESS
    return_info.msg_code = 200
    return_info.msg = "错误删除成功"
    return_info.data = ""
    return return_info.todict()


# 删除多条错误,在MongoDB内
@router.post("/errs_analysis/err_client_fail_del_many")
async def get_client_fai(input: InputPlatformModel[ClientGetFail]):
    """
    逻辑为对传入的数据进行删除, 顺序为  先删除MongoDB内对应的错误, 然后删除mysql内
    记录id的数据, 最后删除对应的错误分析记录信息\n
    ids:20210618160956750662;20210618161112472333
    err_type_name:chaoxingjournal_chaoxinghomeclass_MSG400
    batch:20210621_133344
    name_counts: 0,1,2  (注释:该数据为分段式记录id,以★切割后的末位数据;exp: chaoxingjournal_chaoxingissue_MSG400★0,chaoxingjournal_chaoxingissue_MSG400★1,
                         chaoxingjournal_chaoxingissue_MSG400★2)
    :return:
    """
    return_info = ReturnInfo()
    err_type_name = input.data.err_type_name
    ids = input.data.ids
    batch = input.data.batch
    name_counts = input.data.name_counts
    client_api_fail = Coll().get_errs()
    for _id in ids.split(";"):
        client_api_fail.delete_one({"_id": ObjectId(_id)})
    for name_count in name_counts.split(","):
        err_type_name_af = "★".join([err_type_name, name_count])
        await task_delete(err_type_name_af, batch)
    await task_delete(err_type_name, batch)

    return_info.status = SUCCESS
    return_info.msg_code = 200
    return_info.msg = "错误删除成功"
    return_info.data = ""
    return return_info.todict()


# ----------------------------------------------------------------------------------------------------------------
# client_except 表区
# ----------------------------------------------------------------------------------------------------------------

# 获取错误的id, 以便后续删除
@router.post("/errs_analysis/err_client_except_find")
async def get_client_except(input: InputPlatformModel[CountPost]):
    '''
    针对client_except
    :return:
    '''
    return_info = ReturnInfo()
    page_counts = input.data.page_counts
    counts = input.data.counts
    jump_counts = page_counts * counts
    sql = f"SELECT err_type, batch, err_str FROM `err_analysis` where type_name = 'client_except' and id >= (SELECT id FROM `err_analysis` where type_name = 'client_except' ORDER BY id LIMIT {jump_counts}, 1) limit {counts}"
    sql_count = "SELECT count(*) from err_analysis where type_name = 'client_except'"
    from main import app
    pool = app.state.pool
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(sql)
            data = await cur.fetchall()
            await cur.close()
            conn.close()
    from main import app
    pool = app.state.pool
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(sql_count)
            whole = await cur.fetchone()
            await cur.close()
            conn.close()
    return_info.status = SUCCESS
    return_info.msg_code = 200
    return_info.msg = f"共有条数: {whole[0]}"
    return_info.data = data
    return return_info.todict()


@router.post("/errs_analysis/err_client_except_del_one")
async def get_server_except(input: InputPlatformModel[ServerGetExceptSqlId]):
    '''
    :param input: 删除单条错误,在MongoDB内, 针对client_except表
    :return:
    '''
    return_info = ReturnInfo()
    _id = input.data.ids
    client_api_fail = Coll().get_except_client()
    client_api_fail.delete_one({"_id": ObjectId(_id)})
    return_info.status = SUCCESS
    return_info.msg_code = 200
    return_info.msg = "错误删除成功"
    return_info.data = ""
    return return_info.todict()


# 删除多条错误,在MongoDB内
@router.post("/errs_analysis/err_client_except_del_many_use_batch")
async def get_server_except(input: InputPlatformModel[ServerGetExceptSqlBatch]):
    '''

    :param input:\n
                删除多条错误,在MongoDB内 针对client_except表
    :return:
    '''
    return_info = ReturnInfo()
    batchs = input.data.batchs
    err_type_name = "exception_client_except"
    type_name = "client_except"
    client_api_fail = Coll().get_except_client()
    for batch in batchs.split(","):
        data = await get_mysql(type_name, batch)
        if data == 0:
            return_info.status = SUCCESS
            return_info.msg_code = 200
            return_info.msg = "无此batch号的错误,可能已被删除过,请检查是否重复"
            return_info.data = data
            return return_info.todict()
        else:
            for dat in data:
                for _id in dat[0].split(";"):
                    client_api_fail.delete_one({"_id": ObjectId(_id)})
                await task_delete(err_type_name, batchs)
    return_info.status = SUCCESS
    return_info.msg_code = 200
    return_info.msg = "错误删除成功"
    return_info.data = ""
    return return_info.todict()


# ----------------------------------------------------------------------------------------------------------------
# server_exception表区
# ----------------------------------------------------------------------------------------------------------------


# # 删除多条错误,在MongoDB内
# @router.post("/errs_analysis/err_server_except_del_many_use_id")
# async def get_server_except(input: InputPlatformModel[ServerGetExcept]):
#     '''
#     该API需要传入一堆ID 来进行删除, 没想好是否启用, 暂时先不用这个API    使用另一个
#     :param input: 删除多条错误,在MongoDB内
#     :return:
#     '''
#     return_info = ReturnInfo()
#     err_type_name = input.data.err_type_name
#     ids = input.data.ids
#     batch = input.data.batch
#     server_api_fail = Coll().get_server_exception()
#     for _id in ids.split(";"):
#         server_api_fail.delete_one({"_id": ObjectId(_id)})
#     await task_delete(err_type_name, batch)
#     return_info.status = SUCCESS
#     return_info.msg_code = 200
#     return_info.msg = "错误删除成功"
#     return_info.data = ""
#     return return_info.todict()


# 删除多条错误,在MongoDB内
@router.post("/errs_analysis/err_server_except_del_many_use_batch")
async def get_server_except(input: InputPlatformModel[ServerGetExceptSqlBatch]):
    '''

    :param input: 删除多条错误,在MongoDB内
    :return:
    '''
    return_info = ReturnInfo()
    batchs = input.data.batchs
    err_type_name = "exception_server_except"
    type_name = "server_except"

    server_api_fail = Coll().get_server_exception()
    for batch in batchs.split(","):
        data = await get_mysql(type_name, batch)
        if data == 0:
            return_info.status = SUCCESS
            return_info.msg_code = 200
            return_info.msg = "无此batch号的错误,可能已被删除过,请检查是否重复"
            return_info.data = data
            return return_info.todict()
        else:
            for dat in data:
                for _id in dat[0].split(";"):
                    server_api_fail.delete_one({"_id": ObjectId(_id)})
                await task_delete(err_type_name, batch)
    return_info.status = SUCCESS
    return_info.msg_code = 200
    return_info.msg = "错误删除成功"
    return_info.data = ""
    return return_info.todict()


@router.post("/errs_analysis/err_server_except_del_one")
async def get_server_except(input: InputPlatformModel[ServerGetExceptSqlId]):
    '''
    :param input: 删除单条错误,在MongoDB内, 针对server_exception表
    :return:
    '''
    return_info = ReturnInfo()
    _id = input.data.ids
    server_api_fail = Coll().get_server_exception()
    server_api_fail.delete_one({"_id": ObjectId(_id)})
    return_info.status = SUCCESS
    return_info.msg_code = 200
    return_info.msg = "错误删除成功"
    return_info.data = ""
    return return_info.todict()


# 获取错误的id, 以便后续删除
@router.post("/errs_analysis/err_server_except_find")
async def get_server_except(input: InputPlatformModel[CountPost]):
    '''
        针对server_except
    :return:
    '''
    return_info = ReturnInfo()
    page_counts = input.data.page_counts
    counts = input.data.counts
    jump_counts = page_counts * counts
    sql = f"SELECT err_type, batch, err_str FROM `err_analysis` where type_name = 'server_except' and id >= (SELECT id FROM `err_analysis` where type_name = 'server_except' ORDER BY id LIMIT {jump_counts}, 1) limit {counts}"
    sql_count = "SELECT count(*) from err_analysis where type_name = 'server_except'"
    from main import app
    pool = app.state.pool
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(sql)
            data = await cur.fetchall()
            await cur.close()
            conn.close()
    from main import app
    pool = app.state.pool
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(sql_count)
            whole = await cur.fetchone()
            await cur.close()
            conn.close()
    return_info.status = SUCCESS
    return_info.msg_code = 200
    return_info.msg = f"共有条数: {whole[0]}"
    return_info.data = data
    return return_info.todict()


@router.get("/errs_analysis/err_server_except_del_all")
async def get_server_except():
    '''
    针对server_except, 删除所有的错误,清空
    :return:
    '''
    return_info = ReturnInfo()
    sql = f"select batch from err_analysis where type_name = 'server_except'"
    data_list = list()
    url = get_settings().DEL_MONGO_ERR
    from main import app
    pool = app.state.pool
    async with pool.acquire() as conn:
        async with conn.cursor() as cur:
            await cur.execute(sql)
            data = await cur.fetchall()
            await cur.close()
            conn.close()

    for dat in data:
        data_list.append(dat[0])
    batchs = ",".join(data_list)
    datas = InputPlatformModel[ServerGetExceptSqlBatch](
        data=ServerGetExceptSqlBatch(
            batchs=batchs,
        )
    ).json()
    rrq = AioHttpRequest()
    rrq.set_url(url) \
        .set_timeout(30) \
        .set_data(datas) \
        .set_middler_list(
        [rrq.status_code_middlerwares])
    bools, dicts = await rrq.run(MRequest.POST)
    if bools:
        return_info.status = SUCCESS
        return_info.msg_code = 200
        return_info.msg = "错误删除成功"
        return_info.data = ""
        return return_info.todict()
    else:
        return_info.status = FAILED
        return_info.msg_code = 200
        return_info.msg = "错误删除失败"
        return_info.data = ""
        return return_info.todict()


# ----------------------------------------------------------------------------------------------------------------
# 综合表区
# ----------------------------------------------------------------------------------------------------------------


@router.post("/errs_analysis/err_mongo_del_many")
async def get_server_except(input: InputPlatformModel[DelFromMongo]):
    '''

    :param input:\n
            key_name: MongoDB的键;
            value_name: key_name的值(条件);
            database: MongoDB的表名
            stat: 限定 0, 1; 0为不限制, 1为限制MongoDB表中stat的值为1(条件)
            like: 限定 0, 1; 0表示删除元素为完全匹配, 1表示删除元素为包含在内, 以mysql的语法解释就是  0(=), 1(like) 默认为0
            err_time: 日期, err_time_type为 0 时可为空
                        err_time_type为 1 示例: 20210621,20210622,20210623,20210624;
                        err_time_type为 2 示例: 20210621,20210624     即开始日期和结束日期
            err_time_type: 限定 .0, 1, 2; 0表示默认不以时间为触发时间进行删除  1 表示方式以 , 进行切割并以此进行循环,
                            2表示时间区间

    :return:
    '''
    return_info = ReturnInfo()
    key_name = input.data.key_name
    value_name = input.data.value_name
    database = input.data.database
    stat = input.data.stat
    like = input.data.like
    err_time_type = input.data.err_time_type
    err_time = input.data.err_time
    err_time = err_time.replace("，", ",").replace(" ", "")
    data_name = ""
    data_list = list()
    # 先判定具体是哪张表, 目前仅对三张表进行处理,原则上这个API是可以对所有的表进行处理,但目前无要求的情况下, 仅保持三张表
    if database == "server_exception":
        data_name = Coll().get_server_exception()
    if database == "client_except":
        data_name = Coll().get_except_client()
    if database == "client_api_fail":
        data_name = Coll().get_request_api_fail()
    if database == "test":
        data_name = Coll().get_errs()
    if data_name == "":
        return_info.status = FAILED
        return_info.msg_code = 200
        return_info.msg = "未输入mongo表名,或输入错误"
        return_info.data = ""
        return return_info.todict()
    else:
        # err_time_type  0表示默认不以时间为触发时间进行删除  1 表示方式以 , 进行切割并以此进行循环, 2表示时间区间
        if err_time_type == "0":
            # like判断删除元素是完全匹配还是包含关系, 以mysql的语法解释就是  0(=), 1(like) 默认为0

            if like == "0":
                # stat 判断删除元素是否是程序处理过的错误, 0 表示删除全部匹配, 1表示删除同时还需匹配stat为1 即已被处理过的 默认为1

                if stat == "0":
                    data_name.delete_many({key_name: value_name})
                    return_info.status = SUCCESS
                    return_info.msg_code = 200
                    return_info.msg = "所有符合条件的错误删除成功"
                    return_info.data = ""
                    return return_info.todict()
                elif stat == "1":
                    if database == "client_api_fail":
                        data_name.delete_many({key_name: value_name, "task_info.stat": 1})
                    else:
                        data_name.delete_many({key_name: value_name, "stat": 1})
                    return_info.status = SUCCESS
                    return_info.msg_code = 200
                    return_info.msg = "已处理的错误删除成功"
                    return_info.data = ""
                    return return_info.todict()
                else:
                    return_info.status = FAILED
                    return_info.msg_code = 200
                    return_info.msg = "输入参数错误,请检查, stat参数只能是 0 或者 1, like参数也只能是0 或者1"
                    return_info.data = ""
                    return return_info.todict()
            elif like == "1":
                if stat == "0":
                    data_name.delete_many({key_name: {"$regex": value_name}})
                    return_info.status = SUCCESS
                    return_info.msg_code = 200
                    return_info.msg = "所有符合条件的错误删除成功[包含关系]"
                    return_info.data = ""
                    return return_info.todict()
                elif stat == "1":
                    if database == "client_api_fail":
                        data_name.delete_many({key_name: {"$regex": value_name}, "task_info.stat": 1})
                    else:
                        data_name.delete_many({key_name: {"$regex": value_name}, "stat": 1})
                    return_info.status = SUCCESS
                    return_info.msg_code = 200
                    return_info.msg = "已处理的错误删除成功[包含关系]"
                    return_info.data = ""
                    return return_info.todict()
                else:
                    return_info.status = FAILED
                    return_info.msg_code = 200
                    return_info.msg = "输入参数错误,请检查, stat参数只能是 0 或者 1, like参数也只能是0 或者1"
                    return_info.data = ""
                    return return_info.todict()
        else:
            key_name = "write_time"
            if err_time_type == "1":
                for one_day in err_time.split(","):
                    one_day_format = time_solve(one_day)
                    data_list.append(one_day_format)
            elif err_time_type == "2":
                start_day = err_time.split(",")[0]
                end_day = err_time.split(",")[1]
                for one_day in MCalendar().get_days(start_day, end_day):
                    one_day = BaseTime().datetime_to_string(one_day, format="%Y-%m-%d")
                    data_list.append(one_day)
            else:
                return_info.status = FAILED
                return_info.msg_code = 200
                return_info.msg = "输入参数错误,请检查err_time_type参数  该参数只能是 0 1 2"
                return_info.data = ""
                return return_info.todict()

            # stat 判断删除元素是否是程序处理过的错误, 0 表示删除全部匹配, 1表示删除同时还需匹配stat为1 即已被处理过的 默认为1
            if stat == "0":
                for every_day in data_list:
                    data_name.delete_many({key_name: {"$regex": every_day}})
                return_info.status = SUCCESS
                return_info.msg_code = 200
                return_info.msg = "所有符合条件的错误删除成功[时间关系只有包含关系]"
                return_info.data = ""
                return return_info.todict()
            elif stat == "1":
                if database == "client_api_fail":
                    for every_day in data_list:
                        data_name.delete_many({key_name: {"$regex": every_day}, "task_info.stat": 1})
                else:
                    for every_day in data_list:
                        data_name.delete_many({key_name: {"$regex": every_day}, "stat": 1})
                return_info.status = SUCCESS
                return_info.msg_code = 200
                return_info.msg = "已处理的错误删除成功[时间关系只有包含关系]"
                return_info.data = ""
                return return_info.todict()
            else:
                return_info.status = FAILED
                return_info.msg_code = 200
                return_info.msg = "输入参数错误,请检查, stat参数只能是 0 或者 1"
                return_info.data = ""
                return return_info.todict()

# ----------------------------------------------------------------------------------------------------------------
# mysql   err_except_data表区
# ----------------------------------------------------------------------------------------------------------------
